#include <QDebug>
#include <QMessageBox>
#include <QSqlQuery>
#include <QSqlError>
#include <QDate>
#include "productmanagerdialog.h"
#include "ui_productmanagerdialog.h"
#include "producteditdialog.h"

ProductManagerDialog::ProductManagerDialog(QWidget *parent, QSqlDatabase db)
    : QDialog(parent)
    , ui(new Ui::ProductManagerDialog)
    , db_(db)
{
    ui->setupUi(this);

    ui->treeWidget->setColumnWidth(0, 400);
    ui->treeWidget->setColumnWidth(1, 150);
    ui->treeWidget->setColumnWidth(2, 100);
    ui->treeWidget->setColumnWidth(3, 100);

    initializeList();
}

ProductManagerDialog::~ProductManagerDialog()
{
    delete ui;
}

void ProductManagerDialog::initializeList()
{
    int currentID = 0;
    QTreeWidgetItem* currentItem = ui->treeWidget->currentItem();
    if (currentItem)
        currentID = currentItem->data(0, Qt::UserRole).toInt();

    ui->treeWidget->clear();

    QString q = QString("select p.id, p.name, p.orderno, p.start, p.end, c.name, cl.name, p.sortorder from PRODUCT as p, CLIENTUSERS as cl, COMPANY AS c where p.clientid=cl.id and cl.companyid=c.id");
    if (ui->showClosedCheckBox->isChecked() == false)
        q += " and p.closed='0'";
    q += " order by P.sortorder";
    QSqlQuery query = db_.exec(q);
    if (query.lastError().isValid()) {
        qDebug() << query.lastError().text();
        return;
    }

    while (query.next()) {
        int id = query.value(0).toInt();
        QString name = query.value(1).toString();
        QString orderNumber = query.value(2).toString();
        QString startDate = query.value(3).toDate().toString(Qt::ISODate);
        QString endDate = query.value(4).toDate().toString(Qt::ISODate);
        QString company = query.value(5).toString();
        QString user = query.value(6).toString();
        QStringList strings = QStringList() << name << orderNumber << startDate << endDate << company << user;
        QTreeWidgetItem* item = new QTreeWidgetItem(strings);
        item->setData(0, Qt::UserRole, id);
        ui->treeWidget->addTopLevelItem(item);

        if (id == currentID)
            ui->treeWidget->setCurrentItem(item);
    }
}

void ProductManagerDialog::on_showClosedCheckBox_clicked()
{
    initializeList();
}

void ProductManagerDialog::on_addPushButton_clicked()
{
    ProductEditDialog dlg(this, db_);
    if (dlg.exec() == QDialog::Accepted)
        initializeList();
}

void ProductManagerDialog::on_removePushButton_clicked()
{
    QTreeWidgetItem* item = ui->treeWidget->currentItem();
    if (item == 0)
        return;

    QString name = item->text(0);
    QString orderNumber = item->text(1);
    QMessageBox::StandardButton ret = QMessageBox::information(this, QString(), tr("Are you sure you want to delete selected item?\n\nProduct name: %1\nOrder Number: %2").arg(name).arg(orderNumber), QMessageBox::Ok|QMessageBox::Cancel);
    if (ret != QMessageBox::Ok)
        return;

    int id = item->data(0, Qt::UserRole).toInt();

    db_.exec("BEGIN IMMEDIATE");

    QSqlQuery query = db_.exec( QString("delete from PRODUCT where id='%1'").arg(id) );
    if (query.lastError().isValid()) {
        qDebug() << query.lastError().text();
        db_.exec("ROLLBACK");
        return;
    }

    query = db_.exec( QString("delete from PRODUCTTASK where prodid='%1'").arg(id) );
    if (query.lastError().isValid()) {
        qDebug() << query.lastError().text();
        db_.exec("ROLLBACK");
        return;
    }

    query = db_.exec( QString("delete from PRODUCTCOLOR where prodid='%1'").arg(id) );
    if (query.lastError().isValid()) {
        qDebug() << query.lastError().text();
        db_.exec("ROLLBACK");
        return;
    }

    db_.exec("COMMIT");

    initializeList();
}

void ProductManagerDialog::on_treeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column)
{
    int id = item->data(0, Qt::UserRole).toInt();

    ProductEditDialog dlg(this, db_, id);
    if (dlg.exec() == QDialog::Accepted)
        initializeList();
}

void ProductManagerDialog::on_moveUpPushButton_clicked()
{
    QTreeWidgetItem* item = ui->treeWidget->currentItem();
    if (item == NULL)
        return;

    int id = item->data(0, Qt::UserRole).toInt();
    QSqlQuery query = db_.exec( QString("select sortorder from PRODUCT where id=%1").arg(id) );
    if (query.lastError().isValid()) {
        qDebug() << query.lastError().text();
        return;
    }

    if (query.next() == false)
        return;

    int sortOrder = query.value(0).toInt();
    if (sortOrder <= 1)
        return;

    db_.exec("BEGIN IMMEDIATE");

    query = db_.exec( QString("UPDATE PRODUCT SET sortorder=%1 where sortorder=%2").arg(sortOrder).arg(sortOrder-1) );
    if (query.lastError().isValid()) {
        qDebug() << query.lastError().text();
        db_.exec("ROLLBACK");
        return;
    }

    query = db_.exec( QString("UPDATE PRODUCT SET sortorder=%1 where id=%2").arg(sortOrder-1).arg(id) );
    if (query.lastError().isValid()) {
        qDebug() << query.lastError().text();
        db_.exec("ROLLBACK");
        return;
    }

    db_.exec("COMMIT");

    initializeList();
}

void ProductManagerDialog::on_moveDownPushButton_clicked()
{
    QTreeWidgetItem* item = ui->treeWidget->currentItem();
    if (item == NULL)
        return;

    // get max value of sortorder
    QSqlQuery query = db_.exec("select max(sortorder) from PRODUCT");
    if (query.lastError().isValid()) {
        qDebug() << query.lastError().text();
        return;
    }

    if (query.next() == false)
        return;

    int maxSortOrder = query.value(0).toInt();

    // get sortorder of current item
    int id = item->data(0, Qt::UserRole).toInt();
    query = db_.exec( QString("select sortorder from PRODUCT where id=%1").arg(id) );
    if (query.lastError().isValid()) {
        qDebug() << query.lastError().text();
        return;
    }

    if (query.next() == false)
        return;

    int sortOrder = query.value(0).toInt();
    if (sortOrder == maxSortOrder)
        return;

    db_.exec("BEGIN IMMEDIATE");

    query = db_.exec( QString("UPDATE PRODUCT SET sortorder=%1 where sortorder=%2").arg(sortOrder).arg(sortOrder+1) );
    if (query.lastError().isValid()) {
        qDebug() << query.lastError().text();
        db_.exec("ROLLBACK");
        return;
    }

    query = db_.exec( QString("UPDATE PRODUCT SET sortorder=%1 where id=%2").arg(sortOrder+1).arg(id) );
    if (query.lastError().isValid()) {
        qDebug() << query.lastError().text();
        db_.exec("ROLLBACK");
        return;
    }

    db_.exec("COMMIT");

    initializeList();
}
